<?php
/**
 * TinyMVC - TinyMVCViewRenderer.class.php file
 * 
 * @author Adrian Wieczorek <adi(at)tinymvc(dot)org>
 * @package TinyMVC
 * @version $Id: TinyMVCViewRenderer.class.php 3 2007-09-11 12:08:07Z adi3ek $
 * 
 */

/**
 * Simple view renderer class
 * @package TinyMVC
 * 
 */
class TinyMVCViewRenderer {
 protected $viewsFolderPath;

	/**
	 * @param string $viewsFolderPath views folder path
	 */
	public function __construct($viewsFolderPath = "") {
		try {
			// constructor is called outside TinyMVCFrontController try-catch block, so we need another one here
			$this->viewsFolderPath = $viewsFolderPath;
			if(empty($this->viewsFolderPath) && defined('TINYMVC_PROJECT_VIEWS_PATH')) {						
				$this->viewsFolderPath = TINYMVC_PROJECT_VIEWS_PATH;
			}
			else {
				throw new TinyMVCException("Undefined TINYMVC_PROJECT_VIEWS_PATH");							      	      			
			}
			
			if(!file_exists($this->viewsFolderPath)) {
				throw new TinyMVCException("Incorrect view folder: " . $this->viewsFolderPath);
			}
		}
		catch(Exception $exception) {
			$exception->handleException();
		}
 }

	/**
	 * render view
	 * @param TinyMVCModelAndView $modelAndView model and view transfer object
	 * @return string response page source
	 */
	public function render(TinyMVCModelAndView $modelAndView) {
		$model = $modelAndView->getModel();
  
  // create new view container with full path names
  $view = new TinyMVCSimpleContainer;
  $mainViewPath = false;
  foreach($modelAndView->getView()->getElements() as $key => $viewFile) {
  	$viewFilePath = $this->viewsFolderPath . '/' . $viewFile;
  	if(!$mainViewPath) {
  		$mainViewPath = $viewFilePath;
  	}
  	$view->add($key, $viewFilePath);
  }

		// render view
		if(file_exists($mainViewPath)) {
			ob_start();
			include($mainViewPath);
		 $content = ob_get_contents();
		 ob_end_clean();
		 
			print $content;
		}
		else {
			throw new TinyMVCException("Unable to load base view: $mainViewPath file not found");
		}
	}
}
